<template>
  <div class="components-container"
       v-loading=loading
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-form ref="form" :model="form" :rules="rules" label-width="50px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="概述" prop="overview">
        <el-input v-model="form.overview" placeholder="请输入概述"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="labelId">
        <el-select v-model="form.labelId" placeholder="请选择标签">
          <el-option v-for="item in allLabel" :label="item.title" :value="item.id" ></el-option>
        </el-select>
        <span style="margin-left: 80px;margin-right: 10px">小标签</span>
        <el-button @click="addDomain">新增</el-button>
        <el-button @click="removeDomain(form.tag[form.tag.length-1])">删除</el-button>
      </el-form-item>

<!--      <el-form-item label="小标签" prop="tag">-->
<!--        <el-input v-model="form.tag" placeholder="多个小标签以','分隔"></el-input>-->
<!--      </el-form-item>-->
      <el-row>
        <el-col :span="4"
                v-for="(item, index) in form.tag"
                :key="index">
          <el-form-item>
            <el-input v-model="form.tag[index]" :placeholder="'No'+(index+1)"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="主图">
        <el-row>
          <el-col :span="3">
            <el-upload
              :show-file-list=false
              class="upload-demo"
              :on-change="fileOnChange"
              action="http://localhost"
              :before-upload="beforeUp"
            >
              <el-button size="small" type="primary">{{uploadBut}}</el-button>
            </el-upload>
        </el-col>
        <el-col :span="3">
          <span v-if="imageUrl.length!==0">
            <el-popover
              placement="right"
              width="330"
              trigger="click">
              <el-button  slot="reference" size="small" type="success">查看主图</el-button>
              <img :src="imageUrl" alt="" width="300px" height="180">
            </el-popover>
          </span>
        </el-col>
        <el-col :span="15" style="float:right;">
          <div style="float: right">
            <el-button icon="iconfont el-icon-caogaoxiang" size="mini" type="info" @click="saveDraft">
              草稿
            </el-button>
            <el-button icon="el-icon-upload2" size="mini" type="success" @click="submit">
              发布
            </el-button>
          </div>
        </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <div id = "wangEditor4">
    </div>

<!--    <div>-->
<!--      <tinymce v-model="content" :height="450" @saveDraft="saveDraft" @submit="submit"/>-->
<!--    </div>-->

    <div class="editor-content" v-html="content" />
  </div>
</template>

<script>

// const wangEditorCDN = 'https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js'

import E from 'wangeditor'
import {getToken} from '@/api/qiniu'
import * as qiniu from "qiniu-js";
import {getLabel, submitBlog, saveDraft, getBlogById, updateBlog} from '@/api/blog'

export default {
  name: 'wangEditor2',
  components: { },
  data() {
    return {
      loading: false,
      uploadBut:'点击上传',
      imageUrl:'',
      content:
        `写博客要善于挖坑`,
      allLabel:[],
      form:{
        title:'',
        overview:'',
        labelId:'',
        tag:[''],
        image: ''
      },
      rules:{
        title:[
          { required: true, message: '请输入标题', trigger: 'blur' },
        ],
        overview:[
          { required: true, message: '请输入概述', trigger: 'blur' },
        ],
        labelId:[
          { required: true, message: '请选择标签', trigger: 'change' }
        ]
      },
      editor: null, //编辑器对象
    }
  },
  created(){

    const blogId=this.$route.params.blogId;
    if((this.blogId==null&&blogId!=null)||this.blogId!=null){
      this.blogId=blogId;
      this.loading=true;
      getBlogById(blogId).then(res=>{
        const data=res.data;
        console.log(data)
        this.form.title=data.title;
        this.form.overview=data.overview;
        this.form.labelId=data.labelId;
        this.form.tag=data.tag.split(",");
        this.imageUrl=data.image;
        this.form.image=data.image;
        this.form.content=data.content;
        this.content=data.content;
        this.editor.txt.html(this.content)
        this.loading=false;
      })
    }else{
      const h = this.$createElement;
      this.$notify({
        title: '警告',
        message: h('i', { style: 'color: teal'}, '未选择目标博客'),
        type: 'warning',
        duration: 2000
      });
    }
    getLabel().then(res => {
      console.log(res)
      this.allLabel = res.data;
    })
  },
  mounted() {
    this.initEditor()
  },
  destroyed() {
    this.editor.destroy()
    this.editor = null
  },
  methods:{
    initEditor(){
      const _this = this
      const editor = new E(document.getElementById('wangEditor4'))
      editor.config.zIndex = 1
      editor.config.height = 500
      editor.config.placeholder = this.content
      editor.config.focus = false
      editor.config.lineHeights = ['0.5', '1', '1.15', '1.6', '2', '2.5', '3']
      editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        const imageUrls = await _this.uploadImage(resultFiles)
        // 上传图片，返回结果，将图片插入到编辑器中
        for (let i = 0; i < imageUrls.length; i++) {
          insertImgFn(imageUrls[i])
        }
      }
      editor.create()
      this.editor = editor
      if(this.form.content != null) {
        editor.txt.html(this.form.content)
      }
    },
    async uploadImage(resultFiles) {
      console.log(resultFiles)
      const _this = this
      this.loading = true
      let error = false;
      const imageUrls = []
      for (let i = 0; i < resultFiles.length; i++) {
        getToken().then(response => {
          console.log(response)
          const token = response.data.qiniu_token;
          const key = response.data.qiniu_key;
          const url = response.data.qiniu_url;
          const file = resultFiles[i];
          const config = {useCdnDomain: true};
          //file文件 ket文件名 token凭证 putExtra上传时的附加信息 config一些配置
          const observable = qiniu.upload(file, key, token, {}, config)
          const observer = {
            next(res) {
            },
            error(err) {
              error = true
              _this.loading = false
              _this.$message.error('出现未知问题，请刷新页面，或者联系程序员')
            },
            complete(res) {
              console.log(res)
              imageUrls.push(url)
            }
          }
          observable.subscribe(observer) // 上传开始
        }).catch(err => {
          error = true
          _this.loading = false
          this.$message.error('出现未知问题，请刷新页面，或者联系程序员')
          console.log(err);
        });
      }
      console.log("等待线")
      for (let j = 0; j < 1000; j++) {
        await this.delayTime(1)
        if (imageUrls.length !== resultFiles.length && !error) {
          // 继续等待
          console.log(imageUrls.length)
          console.log(resultFiles.length)
          console.log('未执行完毕')
        } else {
          console.log("执行完毕")
          break
        }
      }
      this.loading = false
      return imageUrls
    },
    async delayTime (seconds) {
      return new Promise((resolve,reject) => { // return / await 等待执行完
        setTimeout(() => {
          resolve('延迟')
        },seconds * 1000)
      })
    },
    saveDraft(){
      console.log('存为草稿')
      const data=this.examine();
      if(!data){
        return;
      }
      data.status=0;
      data.id=this.blogId;
      this.loading=true
      updateBlog(data).then(res=>{
        console.log(res)
        this.loading=false
        this.$router.replace({name:'blogManagement',params:{
          op:"1"
          }})
      })
    },
    submit(){
      console.log('发布')
      const data=this.examine();
      if(!data){
        return;
      }
      data.status=1;
      data.id=this.blogId;
      this.loading=true
      updateBlog(data).then(res=>{
        console.log(res)
        this.loading=false
        this.$router.replace({name:'blogManagement',params:{
            op:"1"
          }})
      })
    },
    examine(){
      const data={
        title:this.form.title,
        overview:this.form.overview,
        labelId:this.form.labelId,
        tag:this.form.tag,
        image:this.form.image,
        content:this.editor.txt.html()
      }
      console.log(data)
      if(data.title.length===0){
        this.$message.error('请填写标题');
        return false;
      }
      if(data.overview.length===0){
        this.$message.error('请填写概述');
        return false;
      }
      if(data.labelId.length===0){
        this.$message.error('请填写标签');
        return false;
      }
      if(data.tag.length===0){
        this.$message.error('请填写小标签');
        return false;
      }else{
        const tags=data.tag;
        for(let i=0;i<tags.length;i++){
          tags[i]=tags[i].trim();
          console.log(tags[i])
          if(tags[i].length===0||tags[i]===''){
            this.$message.error('请填写有效小标签');
            return false;
          }
        }
      }
      if(data.image.length===0){
        this.$message.error('请上传图片');
        return false;
      }
      if(data.content.length===0){
        this.$message.error('请填写内容');
        return false;
      }
      return data;
    },
    removeDomain(item) {
      if(this.form.tag.length===1) {
        this.$message('至少一条标签');
        return;
      }
      const index = this.form.tag.indexOf(item)
      if (index !== -1) {
        this.form.tag.splice(index, 1)
      }
    },
    addDomain() {
      if(this.form.tag.length===6) {
        this.$message('最多六条标签');
        return;
      }
      this.form.tag.push('');
    },
    beforeUp(file){//都是false
      const isLt5M = file.size / 1024 / 1024 < 5;
      if(!isLt5M){
        this.$message.error('上传图片大小不能超过 5MB!');
      }

      if(file.type.indexOf('image')!==-1) {
        getToken().then(response => {
          console.log(response)
          const token = response.data.qiniu_token;
          const key = response.data.qiniu_key;
          const url = response.data.qiniu_url;
          const config = {useCdnDomain: true};
          //file文件 ket文件名 token凭证 putExtra上传时的附加信息 config一些配置
          const observable = qiniu.upload(file, key, token, {}, config)
          let _this=this;
          const observer = {
            next(res) {
            },
            error(err) {
            },
            complete(res) {
              _this.uploadBut='点击修改';
              _this.imageUrl=url;
              _this.form.image=url;
              _this.$message.success('上传成功!');
              _this.loading=false
            }
          }
          observable.subscribe(observer) // 上传开始
        }).catch(err => {
          this.$message.error('出现未知问题');
          console.log(err);
        });
      }
      else {
        this.$message.error('只能上传图像!');
      }
      return false;//借力,用七牛云sdk上传
    },
    fileOnChange(){
      this.loading=true
    }
  },
}
</script>

<style scoped>
.editor-content{
  margin-top: 20px;
}
</style>

